<?php 	
	session_start();
include_once '../pushing.php';

if ($pushTime == true) {
	if ($_SESSION['UserId'] != 3)
		header('Location: push.php');
}

	if(!isset($_SESSION['UserId']))
	{
		header('Location: login.php');
   		die();
	}
	
	include_once '../Functions/generateQuestions.php';
	require_once '../mysqlConnect.php'; //mysqli database connect
	
	$conn = GetConnection();
	$sql = "SELECT * FROM psychological_test_questions ORDER BY qnumber";
	$result = $conn->query($sql);
	$physchological_symptom_questions = array();
	
	while ($row = $result->fetch_assoc()) {
		$physchological_symptom_questions[] = $row;
	}
	
	//generate all question HTML
	$HTML = generateQuestions($physchological_symptom_questions);
	
	
	function getSectionInfobyID ($id)
	{
		$conn = GetConnection();
		$sql = "SELECT * FROM Section S WHERE S.ID = '$id'";
		$value = $conn->query($sql);
		$rs = $value->fetch_assoc();
		return $rs;	
		$conn->close();
	}
	function getPatientInfobyID($id)
	{
		$conn = GetConnection();
		$sql = "SELECT * FROM Patient WHERE ID ='$id'";
		$value = $conn->query($sql);
		$rs = $value->fetch_assoc();
		return $rs;	
		$conn->close();
	}

	$SectionInfo = getSectionInfobyID (3);
	$patientInfo = getPatientInfobyID($_REQUEST['PatId']);
	
	
	function uploadSymptoms($HTML) {
		
		$conn = GetConnection();
		$answers = array();
		for ($i = 0 ; $i < count($HTML); $i++) {
			
			$answers[] = $_POST[$HTML[$i][0]['answerName']]; 
		}		
		
		$sql = "INSERT INTO psychological_test_answers " .
		"(patient_id, qnumber1, qnumber2, qnumber3, global, record_date) VALUES " . 
		"('" . $_GET['PatId'] . "', " .
		"'$answers[0]', '$answers[1]', '$answers[2]', '$answers[3]', '$answers[4]')";
		
		$conn->query($sql);
		if ($conn->error)
			return $conn->error;
		else
			return true;
		
		/*TODO - make this dynamic - if she adds more questions into the database, the upload function should still work
		for ($i = 0; $i < count($HTML); $i++) {
			$answers[] = $_POST[$HTML[$i][0]['answerName']];
			$answerNum = end(explode("_", $HTML[$i][0]['answerName']));
			print_r(substr($answerNum, 3));
			
			if ($i == count($HTML) - 1) 
				$sql .= ", ";
			else
				$sql .= "";
		}
		*/
			
		$conn->close();
		
	}
	
	if (isset($_REQUEST['isPostBack'])) //if the user has reloaded the page using the submit button
	{
		
	$ValidationErrors = array();

		//automated error checker
		foreach ($HTML as $key => $value) {
			
			if (isset($_POST[$value[0]['answerName']])) {
				
				$ans = $_POST[$value[0]['answerName']];
				
				switch($value[0]['type']) {
					
					case 1: //drop down menu
						if ($ans == 9999) {
							$ValidationErrors[] = array("textId" => $value[0]['textId']);
						}
						break;
					case 2://text input
						if ($ans == '' || $ans == null) {
							$ValidationErrors[] = array("textId" => $value[0]['textId']);
						}
						break;
					case 3://date input
						if ($ans == '' || $ans == null) {
							$ValidationErrors[] = array("textId" => $value[0]['textId']);
						}
						break;
					case 4://medication drop down
						if ($ans == 9999) {
							$ValidationErrors[] = array("textId" => $value[0]['textId']);
						}
						break;
					case 5://test drop down
						if ($ans == 9999) {
							$ValidationErrors[] = array("textId" => $value[0]['textId']);
						}
						break;
				}
			}
		}
		
		
	
		if (!(count($ValidationErrors) > 0)) {
			
			$upload = uploadSymptoms($HTML);	
					
			if (!$upload == true) {
				echo '<script language="javascript" type="text/javascript">
				alert("Coult NOT Upload Psychological Test Record for Patient ' . $patientInfo['PatID'] . ': Database Query Error: '. $upload . '");
				
				function redirect(){
					window.location.href = "Psychological Test.php?PatId=' . $_GET['PatId'] . '";
				}
				redirect();
				</script>';
			} else {
				echo '<script language="javascript" type="text/javascript">
				alert("Symptoms for Patient ' . $patientInfo['PatID'] . ' Successfully Added to Database");
				
				function redirect(){
					window.location.href = "Psychological Test.php?PatId=' . $_GET['PatId'] . '";
				}
				redirect();
				</script>';
			}
		}
		
	}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Psych Test</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script src="../JavaScript/jQueryTabs/js/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="../JavaScript/jQueryTabs/js/jquery-ui-1.8.16.custom.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="../JavaScript/jQueryTabs/css/custom-theme/jquery-ui-1.8.16.custom.css"/>
<link rel="stylesheet" type="text/css" href="../Styler.css"/>
<script type="text/javascript">
		$(document).ready(function() {

			<?php if (isset($ValidationErrors)) { 
					if (count($ValidationErrors) > 0 ) {
						foreach ($ValidationErrors as $key => $value) { ?>
							$("#<?php echo $value['textId'];?>").css('color', 'red');
						<?php } 
					}
				}?>
		});
		
	</script>
</head>

<body>

 	<div id="header">
    	<div class="pageTitleText">Psychological Test</div>
    	<div class="pageTitleText" style="font-size: 1em;">
	        <span class="pageTitleSub">Patient: <?php echo $patientInfo['PatID'];?></span>
	        <span class="pageTitleSub">Date Diagnosed: <?php echo $patientInfo['DateDiagnosed'];?></span>
        </div>
 	</div>  
    
   
	<div id="mainMenu" style="height: 451px;">
    	<ul style="list-style: none outside none;">
	        
	        <li>
    			<a href="choosePatient.php?SID=3" style="font-weight: bold; color: #7C3709;">Choose New Patient</a>
    		</li>

	        <li>
	         	<a href="Add_ICD9.php?PatId=<?php echo $_GET['PatId'];?>">Patient ICD9</a>
	        </li>
	        
	        <li>
	         	<a href="Add Prescription.php?PatId=<?php echo $_GET['PatId'];?>">Patient Prescription</a>
	        </li>
	        
	        <li>
	        	<a href="Physical Symptoms.php?PatId=<?php echo $_GET['PatId'];?>">Physical Symptoms</a>
	        </li>
	        
	        <li>
	        	<a href="Neuropsychological Symptoms.php?PatId=<?php echo $_GET['PatId'];?>">Neuropsychological Symptoms</a>
	        </li>
	        
	        <li>
	        	<a href="Psychological Test.php?PatId=<?php echo $_GET['PatId'];?>"  style="font-weight: bold; color: #FB7D08;">Psychological Test</a> 
	        </li>
	        
	        <li>
	        	<a href="Diagnostic Test.php?PatId=<?php echo $_GET['PatId'];?>">Diagnostic Test</a>
	        </li>
	        
	        <li>
	        	<a href="viewPatient.php?PatId=<?php echo $_GET['PatId'];?>">View Patient Information</a>
	        </li>
	        
	        <li>
	         	<a href="Edit Patient.php?PatId=<?php echo $_GET['PatId'];?>">Edit Patient Information</a>
	        </li>
	        
	        <li>
	        	<a href="Save Information.php?PatId=<?php echo $_GET['PatId'];?>">Save Patient Information</a>
	        </li>
	        
	       <li style="border-bottom: 1px solid #FD9D45;">
	       	 	<del><!--<a href="query.php">-->Query<!--</a>--></del>
	        </li>
	        
	        <li>
	       	 	<a href="home.php">Home</a>
	        </li> 
	         
	        <li>
	       	 	<a href="logout.php">Logout</a>
	        </li>
        </ul>
    </div>           
    
     <?php if(isset($ValidationErrors)) { 

    	if (count($ValidationErrors) > 0) {?>
			
			<div class="noQueryResults">
			    <img src="../Images/error.png" style="float:left; margin: 5px 5px 5px 15px;"></img>
			    <p style="font-weight: bold; line-height: 1; margin: 5px 5px 5px 55px;">Error</p>
				<p style="line-height: 1; margin: 5px 5px 5px 55px;">		
		    	<?php if (count($ValidationErrors) > 1) { 
		    		echo 'Multiple Errors';
		    	} else { 
		    		echo 'Error';
		    	}?>
		    	</p>
			</div>
			
    <?php } }?>
    
   <div class="formContainer"> 
        
		<form name="addPatientForm" method="post" action="<?php echo $_SERVER["PHP_SELF"].'?PatId='.$_REQUEST['PatId'] ?>">
           <input type="hidden" name="isPostBack" value="true" />
           
           <div class="Questions" style="width: 625px; height: 250px;">
           
	            <div class="questionLeftColumn"> 
	                <?php 
	                $i = 0;
	                for ($i; $i < ceil(count($HTML)/2); $i++) {	
	                  	echo $HTML[$i][1];
	                } ?>
				</div>
			    <div class="questionMiddleColumn">
	           		<?php for ($i; $i < count($HTML); $i++) {	
	                   	echo $HTML[$i][1];
	                } ?>
	           </div>
			            
	      </div>
	            
           <input type="submit" value="Submit" class="loginButton" style="margin-top: 0px;"/> <!-- id="finishButton" -->
        </form>
   </div>
    
     
</body>
</html>